// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Platform, Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, TextInput, InteractionManager, PermissionsAndroid, } from 'react-native';


// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'react-native-fetch-blob'

// antd 按需加载
import { Tabs, Toast, Portal, Picker, Checkbox } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { accountSetting, upload } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, CacheImage } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { } from '../../util/images.js';
import { press, pathHead, size, ScreenWidth, hotTextColor, path, initUser, FileUpload, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'

class SetUserInfo extends Component {

  constructor(props) {
    super(props)
    console.log(props)
    this.state = {
      avatarPermiss: false,
      nickname: props.user.nickname,
      avatar: props.user.avatar,
      avatarPic: `${pathHead}${props.user.avatar}`,
      gender: props.user.gender,
      brief: props.user.brief,
    }

  }


  componentDidMount() {
    // 获取用户信息
    if (Platform.OS === 'android') {
      this.requestCameraPermission();
    }
  }

  async requestCameraPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          'title': '需要访问相册',
          'message': '上传头像需要该权限',
        },
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.setState({
          avatarPermiss: true,
        })
      } else {
        this.setState({
          avatarPermiss: false,
        })
      }
    } catch (err) {
      console.warn(err)
    }
  }

  pickBase64Phone() {
    const { token } = this.props
    ImagePicker.openPicker({
      width: 400,
      height: 400,
      cropping: true,
      includeBase64: true,
    }).then(image => {
      console.log(image)
      this.setState({
        avatarPic: `data:${image.mime};base64,${image.data}`
      })
      FileUpload(image).then(res => {
        console.log(res)
        this.setState({
          avatar: res.data[0]
        })
        console.log(res, '上传结果')
      }).catch(error => {
        Toast.info('上传你失败', 2)
        console.log(error, '上传失败')
      })
    }).catch(e => {
    });
  }

  accountSetting() {
    const { avatar, gender, nickname, brief } = this.state
    console.log('校验')
    if (!avatar) {
      Toast.info('请上传头像', 1);
      return;
    }
    if (!nickname) {
      Toast.info('请输入昵称', 1);
      return;
    }
    if (!gender) {
      Toast.info('请选择性别', 1);
      return;
    }
    console.log('开始修改')
    this.loading = Toast.loading('设置中', 0)
    accountSetting({
      avatar: avatar,
      nickname: nickname,
      gender: gender,
      brief: brief,
    }).then(res => {
      console.log(res)
      console.log('完成修改')
      Portal.remove(this.loading)
      Toast.success('修改成功')
      Actions.pop()
      // console.log('login')
      initUser()
    }).catch(error => {
      Portal.remove(this.loading)
      console.log(error, '失败的地方')
      Toast.info(error.message, 2);
    }).finally(() => {
      Portal.remove(this.loading)
    })
  }

  render() {
    const { user } = this.props
    const { avatarPic, nickname, gender, brief } = this.state
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="用户信息"
          back={true}
        />
        <ScrollView style={Style.content}>
          <View style={{
            padding: 15,
            backgroundColor: '#fff'
          }}
          >
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              borderBottomWidth: 1,
              borderBottomColor: '#ececee',
              marginTop: 0,
              paddingBottom: 10,
            }}
            >

              <TouchableOpacity
                onPress={() => this.pickBase64Phone()}
              >
                {avatarPic ?
                  <Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: avatarPic }} />
                  :
                  <View style={{ backgroundColor: '#fff', width: 88, height: 88, borderWidth: 1, borderColor: '#eee', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }}>
                    <Text style={{ fontSize: 40, color: '#fff', lineHeight: 88, }}>+</Text>
                  </View>
                }
              </TouchableOpacity>
            </View>
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              borderBottomWidth: 1,
              borderBottomColor: '#ececee',
              marginTop: 0,
            }}
            >
              <TextInput
                placeholder="请输入昵称"
                defaultValue={nickname}
                placeholderTextColor="#c8c8ca"
                onChangeText={(text) => {
                  this.setState({
                    nickname: text
                  })
                }}
                style={{
                  flex: 1,
                  fontSize: 16,
                  paddingVertical: 16,
                  borderWidth: 0,
                  paddingHorizontal: 5,
                  color: '#3e3e3e',
                }}
                underlineColorAndroid="transparent"
              />
            </View>
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              borderBottomWidth: 1,
              borderBottomColor: '#ececee',
              marginTop: 0,
            }}
            >
              <View style={{ marginHorizontal: 50, marginVertical: 10, }}>
                <Checkbox checked={gender == '男'} onChange={() => this.setState({ gender: '男' })}>男</Checkbox>
              </View>
              <View style={{ marginHorizontal: 50, marginVertical: 10, }}>
                <Checkbox checked={gender == '女'} onChange={() => this.setState({ gender: '女' })} >女</Checkbox>
              </View>
            </View>
            <View style={{
              flexDirection: 'row',
              alignItems: 'center',
              borderBottomWidth: 1,
              borderBottomColor: '#ececee',
              marginTop: 0,
            }}
            >
              <TextInput
                onChangeText={(text) => {
                  this.setState({
                    brief: text
                  })
                }}
                placeholder="请输入简介"
                defaultValue={brief}
                placeholderTextColor="#c8c8ca"
                style={{
                  flex: 1,
                  fontSize: 16,
                  paddingVertical: 16,
                  borderWidth: 0,
                  paddingHorizontal: 5,
                  color: '#3e3e3e',
                }}
                underlineColorAndroid="transparent"
              />
            </View>
            <View style={{ padding: 15, }}>
              <TouchableOpacity
                onPress={() => {
                  this.accountSetting()
                }}
                style={{
                  paddingVertical: 14,
                  paddingHorizontal: 20,
                  backgroundColor: hotTextColor,
                  borderRadius: 6,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Text style={{ fontSize: size(28), color: '#fff', lineHeight: size(30), }}>完成</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </View >
    );
  }
}


export default connect(({ user, token }) => ({
  user, token
}))(pureRender(SetUserInfo))
